import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {Employee} from "@/types/resp/employee";
import employeeApi from '@/api/employeeApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import EmployeeAdd from "@/pages/employee/EmployeeAdd.tsx";
import EmployeeView from "@/pages/employee/EmployeeView.tsx";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";
import PositionSelector from "@/pages/position/PositionSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'
import {getGenderText} from "@/utils/dictTranslator.ts";


const EmployeeList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '员工基本信息列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<Employee[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Employee>> = await employeeApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Employee> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Employee>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName', width: 180},
    {title: '工号', dataIndex: 'employeeNumber', key: 'employeeNumber'},
    {title: '姓名', dataIndex: 'name', key: 'name'},
    {title: '密码', dataIndex: 'password', key: 'password', width: 120},
    {title: '性别', key: 'gender', render: (_, record) => (
        <span>
        {(function () {
          if (record.gender === 1) return '男';
          else if (record.gender === 2) return '女';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '出生日期', key: 'birthDate', width: 120, render: (_, record) => (
      <div>{record.birthDate ? record.birthDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '联系电话', dataIndex: 'contactPhone', key: 'contactPhone', width: 120},
    {title: '邮箱', dataIndex: 'email', key: 'email', width: 200},
    {title: '省', dataIndex: 'provinceName', key: 'province', width: 120},
    {title: '市', dataIndex: 'cityName', key: 'city', width: 120},
    {title: '区', dataIndex: 'areaName', key: 'area', width: 120},
    {title: '家庭地址', dataIndex: 'address', key: 'address', width: 200},
    {title: '聘用日期', key: 'hireDate', width: 120, render: (_, record) => (
      <div>{record.hireDate ? record.hireDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName', width: 120},
    {title: '岗位名称', dataIndex: 'positionName', key: 'positionName', width: 120},
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [employeeAddVisible, setEmployeeAddVisible] = useState(false);
  const [employeeViewVisible, setEmployeeViewVisible] = useState(false);
  const [selectedEmployeeId, setSelectedEmployeeId] = useState(0)
  const [selectedEmployee, setSelectedEmployee] = useState({})

  const onAdd = () => {
    setSelectedEmployeeId(0)
    setEmployeeAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedEmployeeId(id)
    setEmployeeAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      employeeApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: Employee) => {
    setSelectedEmployee(record)
    setEmployeeViewVisible(true)
  };

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };
  const [positionSelectorVisible, setPositionSelectorVisible] = useState(false);
  const findPosition = () => {
    setPositionSelectorVisible(true);
  }
  const handlePositionSelected = (selectedPosition: { positionId?: number; positionName?: string; }) => {
    setPositionSelectorVisible(false)
    if (selectedPosition && 'positionId' in selectedPosition) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      positionId: selectedPosition['positionId'],
      positionName: selectedPosition['positionName'],
      }));
    }
  };
  const handleClosePositionSelector = () => {
    setPositionSelectorVisible(false)
  };

  const handleCloseEmployeeAdd = () => {
    setEmployeeAddVisible(false)
  };

  const handleCloseEmployeeView = () => {
    setEmployeeViewVisible(false)
  };

  const onExport = () => {
    const headers = ['企业名称','工号','姓名','密码','性别','出生日期','联系电话','邮箱','省','市','区','家庭地址','聘用日期','部门名称','岗位名称',]
    employeeApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.enterpriseName,d.employeeNumber,d.name,d.password,getGenderText(d.gender),(d.birthDate ? d.birthDate.format('YYYY-MM-DD') : ''),d.contactPhone,d.email,d.provinceName,d.cityName,d.areaName,d.address,(d.hireDate ? d.hireDate.format('YYYY-MM-DD') : ''),d.departmentName,d.positionName])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="employeeList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="employeeNumber" label="工号">
          <Input maxLength={32} placeholder="请输入工号"/>
        </Form.Item>
        <Form.Item name="name" label="姓名">
          <Input maxLength={64} placeholder="请输入姓名"/>
        </Form.Item>
        <Form.Item name="departmentName" label="部门名称">
          <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
        </Form.Item>
        <Form.Item name="positionName" label="岗位名称">
          <Input.Search placeholder="请选择岗位名称" onSearch={findPosition} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<Employee> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }}
                       scroll={{ x: 'max-content' }}
                       style={{marginTop: 'var(--container-margin)'}} />
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
      <PositionSelector visible={positionSelectorVisible} onPositionSelected={handlePositionSelected} onClosePositionSelector={handleClosePositionSelector} />
      <EmployeeAdd visible={employeeAddVisible} onCloseEmployeeAdd={handleCloseEmployeeAdd} id={selectedEmployeeId} />
      <EmployeeView visible={employeeViewVisible} onCloseEmployeeView={handleCloseEmployeeView} viewRow={selectedEmployee} />
    </div>
  );
};

export default EmployeeList;
